package com.bolao;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import com.CustomClasses.JSONParser;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;


public class LoadingActivity extends Activity {

	private static final String query_user = "http://www.worldcupcompendium.com/android_connect/query_user.php";
	private ProgressBar progressBar;

	private boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
	        setContentView(R.layout.loading);
	        progressBar = (ProgressBar) findViewById(R.id.progressBarLoading);
	        
	        if(isOnline()){
	        new Request(Session.getActiveSession(), "/me", null,HttpMethod.GET,new Request.Callback() {
			    public void onCompleted(Response response) { 		    	
			    	GraphUser graphObjectAs = response.getGraphObjectAs(GraphUser.class);
					MainTabActivity.setUser(graphObjectAs);
					
			    	new QueryUser().execute();	   
			    	progressBar.setVisibility(View.GONE);
			    	startTabActivity();
			    }
			}).executeAsync();
	        
	
	       } 
	    	   else {
	   			// 1. Instantiate an AlertDialog.Builder with its constructor
	   			AlertDialog.Builder builder = new AlertDialog.Builder(this);

	   			// 2. Chain together various setter methods to set the dialog characteristics
	   			builder.setMessage(R.string.no_connection_message)
	   			       .setTitle(R.string.no_connection_title);

	   			// 3. Get the AlertDialog from create()
	   			AlertDialog dialog = builder.create();
	   			dialog.show();
	       }
	}

	private void startTabActivity(){
		startActivity(new Intent(getApplicationContext(), MainTabActivity.class));
	}
	
	class QueryUser extends AsyncTask<Void, String, Void>{

		@Override
		protected Void doInBackground(Void... arg0) {
			JSONParser jParser = new JSONParser();
	    	List<NameValuePair> params = new ArrayList<NameValuePair>();
	    	params.add(new BasicNameValuePair("user_id", MainTabActivity.getUser().getId()));
	    	jParser.makeHttpRequest(query_user, "POST", params);

			return null;
		}	
	}

}
